<template>
  <div :class="['login', 'loginBg1']">
    <!-- <div class="logo-circle"></div> -->
    <!-- <div class="logo-title">宁夏回族自治区地震局</div> -->
    <div :class="['login-box']">
      <img src="../assets/images/logo@2x.png" alt="" class="logo">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">预警终端管理系统</h3>
        <!-- <h4 class="title_login">登录</h4> -->
        <div v-if="iswxLogin">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" :type="passwordOnOff ? 'password' : 'text'" auto-complete="off"
              placeholder="密码" @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
              <svg-icon slot="suffix" @click="hidden" icon-class="eye-close"
                class="el-input__icon input-icon el-input__clear" />
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaOnOff">
            <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
              @keyup.enter.native="handleLogin">
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" />
            </div>
          </el-form-item>
          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 20px 0px;">记住密码
          </el-checkbox>
          <!-- 其他方式登录 start -->

          <el-form-item style="width:100%;">
            <!-- class="logo-but" -->
            <el-button round :loading="loading" size="medium" class="logo-but" style="width:100%;"
              @click.native.prevent="handleLogin">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div style="float: right;" v-if="register">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>

          <div class="other-login">
            <p>其他方式登录</p>
            <span @click="wxLogin"><svg t="1691378565489" class="icon" viewBox="0 0 1024 1024" version="1.1"
                xmlns="http://www.w3.org/2000/svg" p-id="2429" width="200" height="200">
                <path
                  d="M864.256 1023.7952H159.744c-87.8592 0-159.744-71.68-159.744-159.5392V160.3584A160.1536 160.1536 0 0 1 159.744 0.8192h704.512A160.1536 160.1536 0 0 1 1024 160.3584V864.256a160.0512 160.0512 0 0 1-159.744 159.5392z"
                  fill="#09BB07" p-id="2430"></path>
                <path
                  d="M381.2352 148.3776c-173.9776 0-316.5184 118.5792-316.5184 269.0048 0 86.8352 47.36 158.208 126.5152 213.504l-31.6416 95.1296 110.7456-55.3984c39.6288 7.936 71.3728 15.8208 110.8992 15.8208 9.984 0 19.8656-0.512 29.5936-1.2288a236.9536 236.9536 0 0 1-9.728-66.4064c0-138.24 118.784-250.368 269.1584-250.368 10.24 0 20.48 0.7168 30.5152 1.8432-27.5456-127.3344-163.84-221.9008-319.488-221.9008zM277.504 369.8688a43.52 43.52 0 1 1 0-87.04 43.52 43.52 0 0 1 0 87.04z m218.624 0a43.52 43.52 0 1 1 0-87.04 43.52 43.52 0 0 1 0 87.04z"
                  fill="#FFFFFF" p-id="2431"></path>
                <path
                  d="M959.2832 615.1168c0-126.464-126.6176-229.632-268.9024-229.632-150.6304 0-269.312 103.1168-269.312 229.632 0 126.72 118.5792 229.5296 269.312 229.5296 31.5392 0 63.3856-7.8848 95.0272-15.8208l86.784 47.5136-23.808-79.104c63.488-47.616 110.7968-110.6944 110.8992-182.1184z m-351.9488-34.8672a34.5088 34.5088 0 1 1 0-69.0176 34.5088 34.5088 0 0 1 0 69.0176z m172.7488 0a34.5088 34.5088 0 1 1 0-69.0176 34.5088 34.5088 0 0 1 0 69.0176z"
                  fill="#FFFFFF" p-id="2432"></path>
              </svg></span>
          </div>
        </div>
        <div v-else id="wxcode" style="height:200px">

        </div>
        <el-button v-if="!iswxLogin" round size="medium" class="logo-but" style="width:100%;margin: 20px 0;"
          @click="iswxLogin = !iswxLogin">
          <span>账号登录</span>

        </el-button>
        <!-- <qc-login v-else :appid="appid" :self_redirect="'true'" :scope="'snsapi_login'" :theme="'black'"
          :redirect_uri="encodeURIComponent(url + '/wxLogin')" href="data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDE4MHB4O21hcmlnbi10b3A6LThweH0KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KLmltcG93ZXJCb3ggLmluZm8ge2Rpc3BsYXk6IG5vbmU7fQ==" rel="external nofollow" @handleCode="handleCode">
        </qc-login> -->
        <div class="el-login-footer">
          <span>Copyright @ 2023 武汉博远减灾科技股份有限公司</span>
        </div>
      </el-form>
      <!--  底部  -->

    </div>
    <Websocket ref="socket"></Websocket>
    <el-dialog :title="'微信绑定'" :close-on-click-modal="false" :custom-class="'sysDialog'" width="400px" v-if="wxOpen"
      :visible.sync="wxOpen">
      <el-row :gutter="10">
        <el-form ref="bindForm" :model="bindForm" :rules="bindRules" label-width="60px">
          <el-form-item label="账号" prop="userName">
            <el-input v-model="bindForm.userName" type="text" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" prop="passWord">
            <el-input v-model="bindForm.passWord" type="password" placeholder="请输入密码" />
          </el-form-item>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitForm">绑 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { getCodeImg, getWechat, wechatlogin, bindUser } from '@/api/login';
import Cookies from 'js-cookie';
import { encrypt, decrypt } from '@/utils/jsencrypt';
import axios from 'axios'
import { setToken } from '@/utils/auth';
import store from '@/store';
import Websocket from "@/components/webSocket";

// import qcLogin from "@/components/qcLogin/index.vue";
export default {
  name: 'Login',

  data() {
    return {
      userInfo: {},
      wxOpen: false,
      iswxLogin: true,
      codeUrl: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: '',
      },
      appid: "wx744a77c50fd4ffed",
      bindForm: {},
      bindRules: {
        userName: [
          { required: true, trigger: 'blur', message: '请输入您的账号' },
        ],
        passWord: [
          { required: true, trigger: 'blur', message: '请输入您的密码' },
        ],
      },
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: '请输入您的账号' },
        ],
        password: [
          { required: true, trigger: 'blur', message: '请输入您的密码' },
        ],
        code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
      },
      loading: false,
      url: 'https://wdm.boeyo.com',
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      redirect: undefined,
      passwordOnOff: true,
    };
  },
  components: {
    Websocket
  },
  //监听路由可以检测返回的code
  watch: {
    $route: {
      handler: function (route) {
        let code = route.query.redirect.match(/code=([^&]+)/)?.[1]
        if (code) {
          this.getOpenidAndUserinfo(code)
        } else {
          this.redirect = route.query && route.query.redirect;
        }
        console.log(code, ' this.wxCode')
        return
        //本地存储code是因为从其他页面返回vue页面存在缓存需要自定义刷新
        if (this.wxCode == localStorage["wxCode"] && this.wxCode != '') {
          window.location.href = this.redirect_uri//回调地址
        } else {
          localStorage.setItem("wxCode", this.wxCode);//设置b为"isaac"
        }
        if (this.wxCode) {
          let params = {
            code: this.wxCode,
            state: '',
          }
          wechatLogin(params).then(res => {
            if (res.status) {
              //返回参数如果绑定微信返回token正常存储登录未绑定账号返回unionid绑定当然也可以以微信信息为主题自动生成账号
            }
          }).catch(() => {
            //返回失败因为二维码已经被使用过所以需要刷新重新获取
            window.location.href = this.redirect_uri
          });
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
    this.getCookie();

    // let call_back_domain_name = window.location.href,
    //   domain_name_length = call_back_domain_name.indexOf("#") - 1,
    //   DDNS = call_back_domain_name.substring(0, domain_name_length)
    // this.url = encodeURIComponent(DDNS);
    // console.log(this.url, 'this.url')
    // console.log(pa);
  },
  methods: {
    getOpenidAndUserinfo(code) {
      let obj = {
        code: code,
        source: 'web',
        state: 'whjy'
      };
      // axios({
      //   method: 'get',
      //   url: ' https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx744a77c50fd4ffed&secret=46d0f63f2423600a6abcd9e9b9d5f14b&code=' + code + '&grant_type=authorization_code',
      //   // headers: {
      //   //   'content-type': 'application/x-www-form-urlencoded'
      //   // },
      // }).then(async (res) => {
      getWechat(obj).then((res) => {
        this.userInfo = res
        // uni.setStorageSync('userInfo', JSON.stringify(userInfo));
        wechatlogin({ unionId: res.unionid }).then((res1) => {
          if (res1.msg == '未绑定账号') {
            this.$confirm('您的账号尚未进行微信绑定,请先去绑定账号?', '提示', {
              confirmButtonText: '去绑定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.wxOpen = true
            }).catch(() => {
              console.log('取消')
            });
          } else {
            setToken(res1.token);
            store.commit('SET_TOKEN', res1.token);
            Cookies.set('username', res1.userName, { expires: 30 });
            this.$refs.socket.init()
            // store. commit("SET_NAME", );
            this.$router.push({ path: this.redirect || '/' }).catch(() => { });
          }
        });
        // });
      })


    },
    wxLogin() {
      this.iswxLogin = false
      let url = encodeURIComponent(this.url + '/wxLogin')
      console.log(url, 'url')
      setTimeout(() => {
        var obj = new WxLogin({
          self_redirect: false,
          id: "wxcode",//wx组建元素

          appid: 'wx744a77c50fd4ffed',//微信平台开放id

          scope: "snsapi_login",

          redirect_uri: url,//回调地址 encodeURIComponent编码

          state: "",

          style: "black",//黑白样式

          href: "data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDE4MHB4O21hcmlnbi10b3A6LThweH0KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KLmltcG93ZXJCb3ggLmluZm8ge2Rpc3BsYXk6IG5vbmU7fQ=="//通过href base64加密css可以微调样式
        });
      }, 500)
    },
    submitForm() {
      this.$refs.bindForm.validate((valid) => {
        if (valid) {
          this.bindForm.unionId = this.userInfo.unionid;
          this.bindForm.sex = this.userInfo.sex;
          this.bindForm.nickname = this.userInfo.nickname;
          this.bindForm.headImgUrl = this.userInfo.headimgurl;
          bindUser(this.bindForm).then((response) => {
            this.$modal.msgSuccess('绑定成功');
            setToken(response.token);
            store.commit('SET_TOKEN', response.token);
            Cookies.set('username', response.userName, { expires: 30 });
            this.$refs.socket.init()
            this.$router.push({ path: this.redirect || '/' }).catch(() => { });
          });
        }
      });
    },
    cancel() {
      this.resetForm("bindForm");
      this.wxOpen = false
    },
    hidden() {
      this.passwordOnOff = !this.passwordOnOff;
    },
    handleCode(data) {
      console.log(data, '123')
    },
    getCode() {
      getCodeImg().then((res) => {
        this.captchaOnOff =
          res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = 'data:image/gif;base64,' + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get('username');
      const password = Cookies.get('password');
      const rememberMe = Cookies.get('rememberMe');
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            // Cookies.set('username', this.loginForm.username, { expires: 30 });
            Cookies.set('password', encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set('rememberMe', this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove('username');
            Cookies.remove('password');
            Cookies.remove('rememberMe');
          }
          this.$store
            .dispatch('Login', this.loginForm)
            .then(() => {
              Cookies.set('username', this.loginForm.username, { expires: 30 });
              this.$refs.socket.init()
              this.$router.push({ path: this.redirect || '/' }).catch(() => { });
            })
            .catch(() => {
              this.loading = false;
              if (this.captchaOnOff) {
                this.getCode();
              }
            });
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login {
  // display: flex;
  // justify-content: center;
  // align-items: center;
  width: 100%;
  height: 100%;
  position: relative;
  // background-size: cover;
}

.logo-but {
  margin-left: 0;
  background-color: rgba(59, 166, 153, 1);
  border: none;
  border-radius: 6px 6px 6px 6px;
  // background-image: linear-gradient(270deg, #76C6FF 0%, rgba(59, 166, 153, 1) 100%);
  // border: 1px solid #76C6FF;
  // border-image: linear-gradient(270deg, #76C6FF 0%, #8676FF 100%);

  &:hover {
    background-image: linear-gradient(270deg, rgba(59, 166, 153, 1) 0%, rgba(59, 166, 153, 1) 100%);
  }
}

.logo-circle {
  position: absolute;
  left: 7.5%;
  top: 7.78%;
  width: 54px;
  height: 54px;
  border-radius: 50%;
  background: #20bbac;
}

.logo-title {
  position: absolute;
  left: 11.15%;
  top: 7.98%;
  // width: 180px;
  height: 51px;
  font-size: 36px;
  font-family: SourceHanSerifSC-Heavy, SourceHanSerifSC;
  font-weight: 800;
  color: #000000;
  line-height: 51px;
}

.loginBg1 {
  // background: url('../assets/images/login-bg@2x.png') no-repeat center center;
  background: url('../assets/images/login-bg@2x.png');
  background-repeat: no-repeat;
  background-size: cover;
  -webkit-background-size: cover;
  -o-background-size: cover;
}

// .loginBg1 {
//   background: url('../assets/images/bg1.png') no-repeat center center;
// }
.title {
  margin: 0px auto 65px auto;
  font-size: 24px;
  background-image: linear-gradient(30deg, #00bf8f 0%, #0092e1 80%);
  -webkit-background-clip: text;
  color: transparent;
  font-family: SourceHanSerifSC-Heavy, SourceHanSerifSC;
  font-weight: 700;
  line-height: 35px;
  text-align: center;
}

.title_login {
  margin-top: 49px;
  font-size: 24px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #fff;
  line-height: 33px;
}

.login-logo {
  // width: 500px;
  position: relative;
  height: 100%;
  background-image: url('../assets/images/login-bg.png');
  background-size: cover;

  .login-logo-title {
    position: absolute;
    top: 7%;
    left: 11.2%;
    width: 332px;
    height: 39px;
    background-image: url('../assets/images/login-title.png');
    background-size: cover;
  }

  .login-logo-body {
    position: absolute;
    top: 35%;
    left: 50%;
    transform: translateX(-50%);
    width: 384px;
    height: 366px;
    background-image: url('../assets/images/login-body.png');
    background-size: cover;
  }
}

.other-login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  color: #fff;

  >span {
    width: 40px;
    height: 40px;
    cursor: pointer;

    >svg {
      width: 100%;
      height: 100%;
    }
  }
}

.but {
  overflow: hidden;
  background: linear-gradient(270deg, rgba(59, 166, 153, 1)1 0%, #00bf8f 100%);
}

.login-box {
  position: absolute;
  top: 15%;
  right: 10%;
  width: 400px;
  height: 600px;
}

.logo {
  position: absolute;
  top: 3%;
  left: 50%;
  transform: translateX(-50%);
  width: 120px;
  // height: 80px;
}

.login-form {
  position: absolute;
  top: 23%;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 15px;
  // background: #ffffff;
  width: 100%;
  padding: 25px 40px 25px 40px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  width: 110%;
  // position: absolute;
  // bottom: 10px;
  // text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 13px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

::v-deep .el-input__inner {
  color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: transparent !important;
}

::v-deep .el-checkbox__label {
  color: #fff;
}

::v-deep .el-checkbox__input.is-checked+.el-checkbox__label {
  color: rgba(59, 166, 153, 1);
}

::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: rgba(59, 166, 153, 1);
  border-color: rgba(59, 166, 153, 1);
}
</style>
